package com.glorious.gcontacts.spring.components;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.glorious.gcontacts.login.exceptions.NotLoggedOnGoogleContactsException;
import com.google.gdata.util.common.net.UriEncoder;

@Component
public class ExceptionHandler implements HandlerExceptionResolver
{

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception)
	{
		if(exception instanceof NotLoggedOnGoogleContactsException)
		{
			try
			{
				response.setStatus(HttpServletResponse.SC_OK);
				response.sendRedirect(String.format("/login/gcontacts/auth?back=%s",UriEncoder.encode(request.getRequestURI())));
			} 
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
		else
		{
			throw new RuntimeException(exception);
		}
		return null;
	}

}
